package com.yinhe.music.yhmusic.music;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hwangjr.rxbus.RxBus;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusNullObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.base.BaseDialoagFragment;
import com.yinhe.music.yhmusic.enums.PlayModeEnum;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.service.PlayService;
import com.yinhe.music.yhmusic.utils.HandlerUtil;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.widget.DividerItemDecoration;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by wm on 2016/2/4.
 */
public class PlayQueueFragment extends BaseDialoagFragment implements View.OnClickListener {

    private static final String TAG = "PlayQueueFragment";

    private TextView tv_playMode, tv_plauNum;
    private ImageView playMode, clearAll;
    private int currentlyPlayingPosition = 0;
    private RecyclerView recyclerView;
    private LinearLayout modeLayout;
    private Context mContext;
    private PlayListAdapter mAdapter;
    private Handler mHandler;
    private PlayModeEnum mode;
    private List<Music> playlist = new ArrayList<>();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置样式
        setStyle(DialogFragment.STYLE_NO_FRAME, R.style.CustomDatePickerDialog);
        mContext = getContext();
        mHandler = HandlerUtil.getInstance(mContext);
    }

    @Override
    public void onStop() {
        super.onStop();

    }

    @Override
    public void onResume() {
        super.onResume();
        if (mService != null) {
            initData();
            recyclerView.scrollToPosition(mService.getPlayingPosition());
        }

    }

    @Override
    public void onServiceConnected(PlayService service) {
        super.onServiceConnected(service);
        if (playlist != null && playlist.isEmpty()) {
            initData();
            recyclerView.scrollToPosition(mService.getPlayingPosition());
        }
    }

    @Override
    protected void onServiceDisconnected() {
        super.onServiceDisconnected();
    }

    private void initData() {
        playlist = mService.getPlayList();
        setPlayNum();
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //设置无标题
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        //设置从底部弹出
        WindowManager.LayoutParams params = getDialog().getWindow()
                .getAttributes();
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setAttributes(params);

        View view = inflater.inflate(R.layout.fragment_queue, container);

        //布局
        tv_playMode  = view.findViewById(R.id.tv_playlist_mode);
        playMode     =  view.findViewById(R.id.image_playlist_mode);
        tv_plauNum   = view.findViewById(R.id.tv_playlist_number);
        recyclerView = view.findViewById(R.id.play_list);
        clearAll     =  view.findViewById(R.id.tv_clear);
        modeLayout   = view.findViewById(R.id.mode_manager);
        mAdapter = new PlayListAdapter();
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(mContext));
        recyclerView.setAdapter(mAdapter);
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST, 20, false));
        //播放模式
        mode = PlayModeEnum.valueOf(Preferences.getPlayMode());
        updateModeView(mode);

        clearAll.setOnClickListener(this);
        modeLayout.setOnClickListener(this);
        return view;
    }

    public void updateModeView(PlayModeEnum mode) {
        if (mode == PlayModeEnum.SHUFFLE) {
            playMode.setImageResource(R.drawable.ic_random_play_blue);
            tv_playMode.setText("随机播放");
        } else if (mode == PlayModeEnum.LOOP) {
            playMode.setImageResource(R.drawable.ic_order_playback_blue);
            tv_playMode.setText("循环播放");
        } else if (mode == PlayModeEnum.ONE) {
            playMode.setImageResource(R.drawable.ic_single_play_blue);
            tv_playMode.setText("单曲循环");
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        int dialogHeight = (int) (mContext.getResources().getDisplayMetrics().heightPixels * 0.6);
        getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, dialogHeight);
        getDialog().setCanceledOnTouchOutside(true);
    }

    private String readTextFromSDcard(InputStream is) throws Exception {
        InputStreamReader reader = new InputStreamReader(is);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuffer buffer = new StringBuffer("");
        String str;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
            buffer.append("\n");
        }
        return buffer.toString();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_clear:
                if (mService != null) {
                    mService.clearPlayList();
                    RxBus.get().post(RxBusEventType.Music.CLEAR_PLAYLIST, RxbusNullObject.INSTANCE);
                }
                dismiss();
                break;
            case R.id.mode_manager:
                PlayModeEnum mode = PlayModeEnum.switchPlayMode();
                updateModeView(mode);
                RxBus.get().post(RxBusEventType.Playing.CHANGE_PLAYING_MODE,mode);
                break;
            default:
                break;
        }
    }

    private class PlayListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
            return new ItemView(layoutInflater.inflate(R.layout.fragment_playqueue_item, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final Music info = playlist.get(position);
            ((ItemView) holder).song.setText(info.getSongName());
            if (info.getSongName()!=null){
                ((ItemView) holder).singer.setText("- "+info.getSingerName());
            } else {
                ((ItemView) holder).singer.setVisibility(View.GONE);
            }

            ((ItemView) holder).delete.setOnClickListener((v) -> {
                if (mService != null) {
                    mService.removeMusicFromPlayList(info);
                    setPlayNum();
                }
            });
            if (mService != null && mService.getPlayingMusic() != null) {
                if (mService.getPlayingMusic().songId == info.songId) {
                    ((ItemView) holder).play.setVisibility(View.VISIBLE);
                    ((ItemView) holder).delete.setVisibility(View.GONE);
                    ((ItemView) holder).song.setTextColor(getResources().getColor(R.color.colorAccent));
                    ((ItemView) holder).singer.setTextColor(getResources().getColor(R.color.colorAccent));
                    currentlyPlayingPosition = position;
                } else {
                    ((ItemView) holder).play.setVisibility(View.GONE);
                    ((ItemView) holder).delete.setVisibility(View.VISIBLE);
                    ((ItemView) holder).song.setTextColor(getResources().getColor(R.color.text_color));
                    ((ItemView) holder).singer.setTextColor(getResources().getColor(R.color.playlist_singer_color));
                }
            }


            ((ItemView) holder).itemView.setOnClickListener((v) -> {
                if (mService != null) {
                    final int a = recyclerView.getChildAdapterPosition(v);
                    mService.playPosition(playlist,a);
                    mHandler.postDelayed(() -> {
                        if (a == -1) {
                            return;
                        }
                        notifyItemChanged(currentlyPlayingPosition);
                        notifyItemChanged(a);
                    }, 200);
                }
            });
        }


        @Override
        public int getItemCount() {

            return playlist.size();
        }

        class ItemView extends RecyclerView.ViewHolder {
            private TextView song,singer;
            private ImageView delete;
            private ProgressBar play;

            public ItemView(View itemView) {
                super(itemView);
                song   = itemView.findViewById(R.id.play_list_song);
                delete = itemView.findViewById(R.id.delete);
                play   = itemView.findViewById(R.id.play_state);
                singer = itemView.findViewById(R.id.play_list_singer);
            }
        }
    }

    private void setPlayNum() {
        mAdapter.notifyDataSetChanged();
        tv_plauNum.setText(getString(R.string.left_brackets) + playlist.size() + getString(R.string.right_brackets));
    }
}
